package com.fyp.client.ptma;

import org.apache.http.HttpResponse;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import com.fyp.client.ptma.model.Downloader;
import com.fyp.client.ptma.model.User;
import com.fyp.client.ptma.utils.Device;
import com.fyp.client.ptma.utils.Helper;
import com.fyp.client.ptma.utils.NetworkConnectivity;
import com.fyp.client.ptma.xml.ResponseXml;
import com.fyp.client.ptma.xml.XmlBuilder;

public class Login extends AbstractActivity
{

	// private View btnAuthenticate;
	private TextView tvDevEmail;
	private TextView tvMyEmail;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setDefaultValues();

	}

	private void setDefaultValues()
	{
		SharedPreferences pref = Login.this.getSharedPreferences(
				Constants.SHARED_PREFERENCE, Context.MODE_PRIVATE);

		String myEmail = Helper.decrypt(pref.getString(
				Constants.PREF_KEY_MYEMAIL, null));

		String devEmail = Helper.decrypt(pref.getString(
				Constants.PREF_KEY_DEVEMAIL, null));

		if (null != myEmail && myEmail.length() > 0)
		{
			tvMyEmail.setText(myEmail);
		}
		if (null != devEmail && devEmail.length() > 0)
		{
			tvDevEmail.setText(devEmail);
		}

	}

	@Override
	public void onBackPressed()
	{

		super.onBackPressed();
	}

	@Override
	int getContentView()
	{
		// TODO Auto-generated method stub
		return R.layout.login;
	}

	@Override
	void initViewRefereces()
	{
		// btnAuthenticate = findViewById(R.id.btnAuthenticate);
		tvDevEmail = (TextView) findViewById(R.id.tvDevEmail);
		tvMyEmail = (TextView) findViewById(R.id.tvMyEmail);

	}

	public void onClick(View view)
	{

		switch (view.getId())
		{
		case R.id.btnAuthenticate:
			new AuthenticationTask().execute();
			break;

		default:
			break;
		}
	}

	private class AuthenticationTask extends
			AsyncTask<Integer, Integer, Integer>
	{

		private static final int INTERNET_CHECK = 0;
		private static final int NO_INTERNET = 1;
		private static final int CHECK_AUTHENTICITY = 2;

		private String myEmail;
		private String devEmail;
		private ProgressDialog pd;

		@Override
		protected void onPreExecute()
		{

			super.onPreExecute();

			pd = new ProgressDialog(Login.this);
			pd.setTitle("Logging in...");
			pd.setMessage("Please wait.");
			pd.setCancelable(false);
			pd.setIndeterminate(true);
			pd.show();

			myEmail = tvMyEmail.getText().toString();
			devEmail = tvDevEmail.getText().toString();

			myEmail = tvMyEmail.getText().toString();
			devEmail = tvDevEmail.getText().toString();
			if (devEmail == null || myEmail == null || devEmail.length() == 0
					|| myEmail.length() == 0)
			{
				cancel(true);
			}

		}

		@Override
		protected void onPostExecute(Integer result)
		{

			super.onPostExecute(result);
			switch (result)
			{
			case ResponseXml.OK:
				SharedPreferences pref = Login.this.getSharedPreferences(
						Constants.SHARED_PREFERENCE, Context.MODE_PRIVATE);

				Editor edit = pref.edit();
				edit.putString(Constants.PREF_KEY_MYEMAIL,
						Helper.encrypt(myEmail)).putString(
						Constants.PREF_KEY_DEVEMAIL, Helper.encrypt(devEmail));
				edit.commit();

				switchScreen(ApplicationsList.class, 0);
				finish();
				break;
			case ResponseXml.NOT_REGISTERED:
				showLongToast(getString(R.string.not_registered));
				finish();
				break;
			}
			pd.dismiss();
		}

		@Override
		protected Integer doInBackground(Integer... arg0)
		{

			publishProgress(INTERNET_CHECK);
			if (!NetworkConnectivity.isConntectedToInternet(Login.this))
			{
				publishProgress(NO_INTERNET);
				return 0;
			}

			// Authenticity Check
			publishProgress(CHECK_AUTHENTICITY);

			String url = getString(R.string.WS_URL)
					+ getString(R.string.WS_LOGIN);

			// Downloader
			Downloader downloader = new Downloader();
			downloader.setDeviceId(Device.getDeviceNumber(Login.this));
			downloader.setDeviceOs(Build.VERSION.RELEASE);
			downloader.setEmail(myEmail);
			User user = new User(devEmail);
			downloader.setUser(user);

			HttpResponse response = NetworkConnectivity.performPostOperation(
					url, XmlBuilder.getXmlForAuthetication(downloader));
			ResponseXml code = null;
			try
			{
				code = Helper.getResponseObject(response);
			} catch (Exception e)
			{
				code = new ResponseXml();
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			// exit but not logged
			if (code.getStatusCode() == ResponseXml.NOT_REGISTERED)
			{

				return ResponseXml.NOT_REGISTERED;
			}
			return ResponseXml.OK;

		}

		@Override
		protected void onProgressUpdate(Integer... values)
		{

			super.onProgressUpdate(values);

		}
	}
}
